import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Space, message, DatePicker, Select, Input, Typography, Row, Col, Statistic, Tag, Tabs, Modal, Descriptions, Spin } from 'antd';
import { ReloadOutlined, DownloadOutlined, SearchOutlined, SyncOutlined, InfoCircleOutlined, LineChartOutlined } from '@ant-design/icons';
import api, { dataAPI } from '../services/api';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import ReactECharts from 'echarts-for-react';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Title, Text } = Typography;
const { Search } = Input;

interface FundDataItem {
  id: number;
  fund_code: string;
  fund_name: string;
  nav: number;
  cumulative_nav: number;
  daily_growth_rate: number;
  nav_date: string;
  updated_at: string;
}

interface NavHistoryItem {
  id?: number;
  nav_date?: string;
  price_date?: string;
  date?: string;
  nav?: number;
  net_value?: number;
  unit_nav?: number;
  unit_value?: number;
  cumulative_nav?: number;
  accumulated_value?: number;
  accumulated_nav?: number;
  cumulative_value?: number;
  daily_growth_rate?: number;
  daily_return?: number;
  daily_rate?: number;
  growth_rate?: number;
  fund_code?: string;
  fund_name?: string;
}

interface FundInfo {
  fund_code: string;
  fund_name: string;
  fund_full_name: string;
  fund_type: string;
  fund_company: string;
  fund_manager: string;
  establishment_date: string;
  latest_scale: string;
  custodian_bank: string;
  rating_agency: string;
  fund_rating: string;
  investment_strategy: string;
  investment_objective: string;
  performance_benchmark: string;
  updated_at: string;
}

interface FundStats {
  total_funds: number;
  total_net_values: number;
  latest_update: string;
  fund_types: { [key: string]: number };
}

interface PaginationInfo {
  current: number;
  pageSize: number;
  total: number;
}

const FundData: React.FC = () => {
  const [data, setData] = useState<FundDataItem[]>([]);
  const [fundInfoData, setFundInfoData] = useState<FundInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<'netvalue' | 'info'>('info');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null);
  const [selectedFunds, setSelectedFunds] = useState<string[]>([]);
  const [searchText, setSearchText] = useState<string>('');
  const [selectedFundCodes, setSelectedFundCodes] = useState<string[]>([]);
  const [fundCodes, setFundCodes] = useState<string[]>([]);
  const [fundSearchText, setFundSearchText] = useState<string>(''); // 基金名称模糊查询
  const [stats, setStats] = useState<FundStats | null>(null);
  const [pagination, setPagination] = useState<PaginationInfo>({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedFundDetail, setSelectedFundDetail] = useState<FundInfo | null>(null);
  const [navHistoryModalVisible, setNavHistoryModalVisible] = useState(false);
  const [selectedFundCode, setSelectedFundCode] = useState<string>('');
  const [navHistoryData, setNavHistoryData] = useState<NavHistoryItem[]>([]);
  const [navHistoryLoading, setNavHistoryLoading] = useState(false);
  const [showChart, setShowChart] = useState(true);
  const [navHistoryPeriod, setNavHistoryPeriod] = useState<string>('all'); // 净值历史时间范围

  // 净值历史表格列定义 - 支持不同的数据字段名
  const navHistoryColumns: ColumnsType<any> = [
    {
      title: '日期',
      dataIndex: 'nav_date',
      key: 'nav_date',
      width: 120,
      render: (value: any, record: any) => {
        const date = record.nav_date || record.price_date || record.date;
        return date ? dayjs(date).format('YYYY-MM-DD') : '-';
      },
    },
    {
      title: '单位净值',
      dataIndex: 'nav',
      key: 'nav',
      width: 120,
      render: (value: any, record: any) => {
        const nav = record.nav || record.net_value || record.unit_nav || record.unit_value || value;
        if (nav === null || nav === undefined) return '-';
        const numValue = typeof nav === 'string' ? parseFloat(nav) : nav;
        return isNaN(numValue) ? '-' : numValue.toFixed(4);
      },
    },
    {
      title: '累计净值',
      dataIndex: 'cumulative_nav',
      key: 'cumulative_nav',
      width: 120,
      render: (value: any, record: any) => {
        const cumulativeNav = record.cumulative_nav || record.accumulated_value || record.accumulated_nav || record.cumulative_value || value;
        if (cumulativeNav === null || cumulativeNav === undefined) return '-';
        const numValue = typeof cumulativeNav === 'string' ? parseFloat(cumulativeNav) : cumulativeNav;
        return isNaN(numValue) ? '-' : numValue.toFixed(4);
      },
    },
    {
      title: '日收益率(%)',
      dataIndex: 'daily_growth_rate',
      key: 'daily_growth_rate',
      width: 120,
      render: (value: any, record: any) => {
        const dailyRate = record.daily_growth_rate || record.daily_return || record.daily_rate || record.growth_rate || value;
        if (dailyRate === null || dailyRate === undefined) return '-';
        const numValue = typeof dailyRate === 'string' ? parseFloat(dailyRate) : dailyRate;
        if (isNaN(numValue)) return '-';
        const color = numValue > 0 ? '#ff4d4f' : numValue < 0 ? '#52c41a' : '#666';
        const prefix = numValue > 0 ? '+' : '';
        return <span style={{ color, fontWeight: 'bold' }}>{prefix}{(numValue * 100).toFixed(2)}%</span>;
      },
    },
  ];

  const netValueColumns: ColumnsType<FundDataItem> = [
    {
      title: '基金代码',
      dataIndex: 'fund_code',
      key: 'fund_code',
      width: 120,
      fixed: 'left',
      render: (fund_code: string, record: FundDataItem) => (
        <Button 
          type="link" 
          onClick={() => handleShowFundDetailAndHistory(fund_code)}
          style={{ padding: 0, height: 'auto' }}
        >
          {fund_code}
        </Button>
      ),
    },
    {
      title: '基金名称',
      dataIndex: 'fund_name',
      key: 'fund_name',
      width: 200,
    },
    {
      title: '单位净值',
      dataIndex: 'nav',
      key: 'nav',
      width: 120,
      render: (value: any) => {
        if (value === null || value === undefined) return '-';
        const numValue = typeof value === 'string' ? parseFloat(value) : value;
        return isNaN(numValue) ? '-' : numValue.toFixed(4);
      },
    },
    {
      title: '累计净值',
      dataIndex: 'cumulative_nav',
      key: 'cumulative_nav',
      width: 120,
      render: (value: any) => {
        if (value === null || value === undefined) return '-';
        const numValue = typeof value === 'string' ? parseFloat(value) : value;
        return isNaN(numValue) ? '-' : numValue.toFixed(4);
      },
    },
    {
      title: '日收益率(%)',
      dataIndex: 'daily_growth_rate',
      key: 'daily_growth_rate',
      width: 120,
      render: (value: any) => {
        if (value === null || value === undefined) return '-';
        const numValue = typeof value === 'string' ? parseFloat(value) : value;
        if (isNaN(numValue)) return '-';
        const color = numValue > 0 ? '#ff4d4f' : numValue < 0 ? '#52c41a' : '#666';
        const prefix = numValue > 0 ? '+' : '';
        return <span style={{ color, fontWeight: 'bold' }}>{prefix}{(numValue * 100).toFixed(2)}%</span>;
      },
      sorter: (a: FundDataItem, b: FundDataItem) => {
        const getRate = (item: FundDataItem) => {
          if (item.daily_growth_rate === null || item.daily_growth_rate === undefined) return -Infinity;
          const numValue = typeof item.daily_growth_rate === 'string' ? parseFloat(item.daily_growth_rate) : item.daily_growth_rate;
          return isNaN(numValue) ? -Infinity : numValue;
        };
        return getRate(a) - getRate(b);
      },
    },
    {
      title: '价格日期',
      dataIndex: 'nav_date',
      key: 'nav_date',
      width: 120,
      render: (value: string) => {
        if (!value) return '-';
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      width: 160,
      render: (value: string) => dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  const fundInfoColumns: ColumnsType<FundInfo> = [
    {
      title: '基金代码',
      dataIndex: 'fund_code',
      key: 'fund_code',
      width: 120,
      fixed: 'left',
      render: (code: string, record: FundInfo) => (
        <Button 
          type="link" 
          onClick={() => handleShowFundDetail(record)}
          style={{ padding: 0, height: 'auto' }}
        >
          {code}
        </Button>
      ),
    },
    {
      title: '基金名称',
      dataIndex: 'fund_name',
      key: 'fund_name',
      width: 250,
      ellipsis: true,
    },
    {
      title: '基金类型',
      dataIndex: 'fund_type',
      key: 'fund_type',
      width: 120,
      render: (type: string) => (
        <Tag color={getTypeColor(type)}>{type}</Tag>
      ),
    },
    {
      title: '管理公司',
      dataIndex: 'fund_company',
      key: 'fund_company',
      width: 200,
      ellipsis: true,
    },
    {
      title: '基金经理',
      dataIndex: 'fund_manager',
      key: 'fund_manager',
      width: 150,
      ellipsis: true,
    },
    {
      title: '成立日期',
      dataIndex: 'establishment_date',
      key: 'establishment_date',
      width: 120,
    },
    {
      title: '基金规模',
      dataIndex: 'latest_scale',
      key: 'latest_scale',
      width: 140,
      render: (value: string) => value || '-',
      sorter: (a: FundInfo, b: FundInfo) => {
        // 提取规模中的数字进行比较（假设格式为"XX.XX亿元"）
        const getScaleValue = (scale: string) => {
          if (!scale || scale === '-') return 0;
          const match = scale.match(/(\d+(?:\.\d+)?)/);
          return match ? parseFloat(match[1]) : 0;
        };
        return getScaleValue(a.latest_scale) - getScaleValue(b.latest_scale);
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      width: 160,
      render: (value: string) => dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  const getTypeColor = (type: string) => {
    const colorMap: { [key: string]: string } = {
      '股票型': 'red',
      '债券型': 'blue',
      '混合型': 'green',
      '货币型': 'orange',
      '指数型': 'purple',
      'QDII': 'cyan',
      'LOF': 'magenta',
      'FOF': 'gold',
    };
    return colorMap[type] || 'default';
  };

  const handleShowFundDetail = (fund: FundInfo) => {
    setSelectedFundDetail(fund);
    setDetailModalVisible(true);
  };

  // 将FundData转换为FundInfo格式
  const convertFundDataToFundInfo = (fundData: any): FundInfo => {
    return {
      fund_code: fundData.fund_code || '',
      fund_name: fundData.fund_name || '',
      fund_full_name: fundData.fund_name || '', // 使用fund_name作为默认值
      fund_type: fundData.fund_type || '',
      fund_company: fundData.fund_company || '',
      fund_manager: fundData.fund_manager || '',
      establishment_date: fundData.establishment_date || '',
      latest_scale: fundData.fund_size ? `${fundData.fund_size}亿元` : '-',
      custodian_bank: '-', // FundData中没有此字段
      rating_agency: '-', // FundData中没有此字段
      fund_rating: '-', // FundData中没有此字段
      investment_strategy: '-', // FundData中没有此字段
      investment_objective: '-', // FundData中没有此字段
      performance_benchmark: '-', // FundData中没有此字段
      updated_at: fundData.updated_at || ''
    };
  };

  const handleShowFundDetailAndHistory = async (fundCode: string) => {
    setSelectedFundCode(fundCode);
    setNavHistoryModalVisible(true);
    setNavHistoryLoading(true);
    
    try {
      // 同时获取基金详情和净值历史数据
      const [fundDetailResponse, navHistoryResponse] = await Promise.all([
        dataAPI.getFund(fundCode).catch(() => null), // 如果获取基金详情失败，不影响净值历史显示
        dataAPI.getFundNavDetailHistory(fundCode, {
          period: navHistoryPeriod // 使用选择的时间范围
        })
      ]);
      
      // 调试日志：查看返回的数据结构
      console.log('navHistoryResponse:', navHistoryResponse);
      console.log('navHistoryResponse.data:', navHistoryResponse?.data);
      
      // 设置净值历史数据 - 处理不同的数据格式
      if (navHistoryResponse?.data) {
        // 如果返回的是数组，直接使用
        if (Array.isArray(navHistoryResponse.data)) {
          setNavHistoryData(navHistoryResponse.data);
        } 
        // 如果返回的是对象，检查是否有results属性
        else if (navHistoryResponse.data.results && Array.isArray(navHistoryResponse.data.results)) {
          setNavHistoryData(navHistoryResponse.data.results);
        }
        // 如果返回的是对象，检查是否有data属性
        else if (navHistoryResponse.data.data && Array.isArray(navHistoryResponse.data.data)) {
          setNavHistoryData(navHistoryResponse.data.data);
        }
        // 其他情况，尝试将整个数据作为数组
        else {
          console.warn('净值历史数据格式未知，尝试转换:', navHistoryResponse.data);
          setNavHistoryData([]);
        }
      } else {
        setNavHistoryData([]);
      }
      
      // 如果成功获取基金详情，转换格式并显示基金详情模态框
      if (fundDetailResponse) {
        const fundInfo = convertFundDataToFundInfo(fundDetailResponse);
        setSelectedFundDetail(fundInfo);
        setDetailModalVisible(true);
      }
    } catch (error) {
      message.error('获取数据失败');
      console.error('Error fetching fund data:', error);
      setNavHistoryData([]);
    } finally {
      setNavHistoryLoading(false);
    }
  };

  const handleShowNavHistory = async (fundCode: string) => {
    setSelectedFundCode(fundCode);
    setNavHistoryModalVisible(true);
    setNavHistoryLoading(true);
    
    try {
      // 获取净值历史数据，使用选择的时间范围
      const response = await dataAPI.getFundNavDetailHistory(fundCode, {
        period: navHistoryPeriod
      });
      
      // 调试日志：查看返回的数据结构
      console.log('navHistoryResponse in handleShowNavHistory:', response);
      console.log('navHistoryResponse.data:', response?.data);
      
      // 设置净值历史数据 - 处理不同的数据格式
      if (response?.data) {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response.data)) {
          setNavHistoryData(response.data);
        } 
        // 如果返回的是对象，检查是否有results属性
        else if (response.data.results && Array.isArray(response.data.results)) {
          setNavHistoryData(response.data.results);
        }
        // 如果返回的是对象，检查是否有data属性
        else if (response.data.data && Array.isArray(response.data.data)) {
          setNavHistoryData(response.data.data);
        }
        // 其他情况，尝试将整个数据作为数组
        else {
          console.warn('净值历史数据格式未知，尝试转换:', response.data);
          setNavHistoryData([]);
        }
      } else {
        setNavHistoryData([]);
      }
    } catch (error) {
      message.error('获取净值历史数据失败');
      console.error('Error fetching nav history:', error);
      setNavHistoryData([]);
    } finally {
      setNavHistoryLoading(false);
    }
  };

  const getChartOption = () => {
    if (!navHistoryData || navHistoryData.length === 0) {
      return {};
    }

    // 调试日志：查看数据结构
    console.log('navHistoryData in getChartOption:', navHistoryData);
    console.log('First item structure:', navHistoryData[0]);

    // 按日期排序数据
    const sortedData = [...navHistoryData].sort((a: NavHistoryItem, b: NavHistoryItem) => {
      const dateA = a.nav_date || a.price_date || a.date;
      const dateB = b.nav_date || b.price_date || b.date;
      return dayjs(dateA).valueOf() - dayjs(dateB).valueOf();
    });

    // 动态获取字段名
    const dates = sortedData.map((item: NavHistoryItem) => {
      const date = item.nav_date || item.price_date || item.date;
      return dayjs(date).format('MM-DD');
    });
    
    // 获取单位净值数据 - 支持不同的字段名
    const unitValues = sortedData.map((item: NavHistoryItem) => {
      const value = item.nav || item.net_value || item.unit_nav || item.unit_value;
      return value !== null && value !== undefined ? Number(value) : null;
    });
    
    // 获取累计净值数据 - 支持不同的字段名
    const accumulatedValues = sortedData.map((item: NavHistoryItem) => {
      const value = item.cumulative_nav || item.accumulated_value || item.accumulated_nav || item.cumulative_value;
      return value !== null && value !== undefined ? Number(value) : null;
    });

    console.log('Chart data - dates:', dates);
    console.log('Chart data - unitValues:', unitValues);
    console.log('Chart data - accumulatedValues:', accumulatedValues);

    return {
      title: {
        text: `${selectedFundCode} 净值走势`,
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: (params: any) => {
          const date = params[0].axisValue;
          let result = `日期: ${date}<br/>`;
          params.forEach((param: any) => {
            result += `${param.seriesName}: ${param.value}<br/>`;
          });
          return result;
        }
      },
      legend: {
        data: ['单位净值', '累计净值'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        scale: true,
        axisLabel: {
          formatter: '{value}'
        }
      },
      series: [
        {
          name: '单位净值',
          type: 'line',
          data: unitValues,
          smooth: true,
          lineStyle: {
            color: '#1890ff',
            width: 2
          },
          itemStyle: {
            color: '#1890ff'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
                { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
              ]
            }
          }
        },
        {
          name: '累计净值',
          type: 'line',
          data: accumulatedValues,
          smooth: true,
          lineStyle: {
            color: '#52c41a',
            width: 2
          },
          itemStyle: {
            color: '#52c41a'
          }
        }
      ]
    };
  };

  const fetchFundNetValueData = async (page: number = 1, pageSize: number = 20) => {
    setLoading(true);
    try {
      const params: any = {
        page,
        page_size: pageSize,
      };
      
      // 如果有搜索文本，作为基金代码过滤条件
      if (searchText) {
        params.fund_code = searchText;
      }
      
      const response = await api.get('/data/fund-nav-detail/latest/', { params });
      
      if (response.data.status === 'success') {
        setData(response.data.data);
        setPagination({
          current: response.data.pagination.current_page,
          pageSize: response.data.pagination.page_size,
          total: response.data.pagination.total_count,
        });
      } else {
        message.error(response.data.message || '获取基金净值数据失败');
      }
    } catch (error) {
      message.error('获取基金净值数据失败');
      console.error('Error fetching fund net value data:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchFundInfoData = async (page: number = 1, pageSize: number = 20) => {
    setLoading(true);
    try {
      const params: any = {
        page,
        page_size: pageSize,
      };
      if (searchText) {
        params.search = searchText;
      }
      if (selectedFunds.length > 0) {
        params.fund_codes = selectedFunds.join(',');
      }
      
      const response = await api.get('/data/funds/', { params });
      
      if (response.data.results) {
        // 后端分页响应
        setFundInfoData(response.data.results);
        setPagination({
          current: page,
          pageSize: pageSize,
          total: response.data.count || 0,
        });
      } else {
        // 非分页响应
        setFundInfoData(response.data);
        setPagination({
          current: 1,
          pageSize: pageSize,
          total: response.data.length,
        });
      }
    } catch (error) {
      message.error('获取基金信息失败');
      console.error('Error fetching fund info data:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      const response = await dataAPI.getFundStatistics();
      setStats(response);
    } catch (error) {
      console.error('Error fetching stats:', error);
    }
  };

  const fetchFundCodes = async () => {
    try {
      const params: any = { page_size: 1000 };
      // 如果输入了基金名称搜索文本，添加到参数中
      if (fundSearchText) {
        params.search = fundSearchText;
      }
      const response = await api.get('/data/funds/', { params });
      const codes = response.data.results?.map((item: any) => item.fund_code || item.code) || [];
      setFundCodes(codes);
    } catch (error) {
      console.error('Error fetching fund codes:', error);
    }
  };

  const handleSync = async () => {
    setLoading(true);
    try {
      await api.post('/data/sync/fund-data/', {
        fund_codes: fundCodes,
        sync_net_value: true
      });
      message.success('数据同步成功');
      if (activeTab === 'info') {
        fetchFundInfoData(pagination.current, pagination.pageSize);
      } else {
        fetchFundNetValueData(pagination.current, pagination.pageSize);
      }
    } catch (error) {
      message.error('数据同步失败');
      console.error('Error syncing data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async () => {
    try {
      const params: any = {};
      if (dateRange && dateRange[0] && dateRange[1]) {
        params.start_date = dateRange[0].format('YYYY-MM-DD');
        params.end_date = dateRange[1].format('YYYY-MM-DD');
      }
      if (selectedFunds.length > 0) {
        params.codes = selectedFunds.join(',');
      }
      
      const response = await api.get('/data/funds/export/', {
        params,
        responseType: 'blob'
      });
      
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `fund_data_${dayjs().format('YYYYMMDD')}.xlsx`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      
      message.success('数据导出成功');
    } catch (error) {
      message.error('数据导出失败');
      console.error('Error exporting data:', error);
    }
  };

  const handleTableChange = (paginationConfig: any) => {
    const { current, pageSize } = paginationConfig;
    if (activeTab === 'info') {
      fetchFundInfoData(current, pageSize);
    } else {
      fetchFundNetValueData(current, pageSize);
    }
  };

  useEffect(() => {
    fetchFundInfoData();
    fetchStats();
    fetchFundCodes();
  }, []);

  useEffect(() => {
    if (activeTab === 'info') {
      fetchFundInfoData(1, pagination.pageSize);
    } else {
      fetchFundNetValueData(1, pagination.pageSize);
    }
  }, [activeTab]);

  // 监听基金名称搜索文本变化，实时更新基金代码列表
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchFundCodes();
    }, 300); // 300ms防抖延迟

    return () => clearTimeout(timer);
  }, [fundSearchText]);

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>基金数据管理</Title>
      
      {stats && (
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={6}>
            <Card>
              <Statistic title="基金总数" value={stats.total_funds} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic title="净值记录数" value={stats.total_net_values} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="最新更新" 
                value={stats.latest_update ? dayjs(stats.latest_update).format('MM-DD HH:mm') : '-'} 
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="基金类型" 
                value={Object.keys(stats.fund_types || {}).length} 
              />
            </Card>
          </Col>
        </Row>
      )}

      <Card>
        <Tabs
          activeKey={activeTab}
          onChange={(key) => setActiveTab(key as 'netvalue' | 'info')}
          items={[
            {
              key: 'info',
              label: (
                <span>
                  <InfoCircleOutlined />
                  基金信息
                </span>
              ),
            },
            {
              key: 'netvalue',
              label: (
                <span>
                  <LineChartOutlined />
                  净值数据
                </span>
              ),
            },
          ]}
        />

        <Space style={{ marginBottom: '16px' }} wrap>
          {activeTab === 'info' && (
            <Search
              placeholder="输入基金名称或代码搜索"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={() => fetchFundInfoData(1, pagination.pageSize)}
              style={{ width: 250 }}
              allowClear
            />
          )}
          {activeTab === 'netvalue' && (
            <>
              <RangePicker
                value={dateRange}
                onChange={(dates) => setDateRange(dates)}
                placeholder={['开始日期', '结束日期']}
              />
              <Search
                placeholder="输入基金名称模糊查询"
                value={fundSearchText}
                onChange={(e) => setFundSearchText(e.target.value)}
                onSearch={fetchFundCodes}
                style={{ width: 200 }}
                allowClear
              />
              <Select
                mode="multiple"
                placeholder="选择基金代码"
                value={selectedFundCodes}
                onChange={setSelectedFundCodes}
                style={{ minWidth: '200px' }}
                options={fundCodes.map(code => ({ label: code, value: code, key: code }))}
              />
            </>
          )}
          {activeTab === 'info' && (
            <Select
              mode="multiple"
              placeholder="选择基金代码"
              value={selectedFunds}
              onChange={setSelectedFunds}
              style={{ minWidth: '200px' }}
              options={fundCodes.map(code => ({ label: code, value: code, key: code }))}
            />
          )}
          <Button
            type="primary"
            icon={<ReloadOutlined />}
            onClick={activeTab === 'info' ? () => fetchFundInfoData(1, pagination.pageSize) : () => fetchFundNetValueData(1, pagination.pageSize)}
            loading={loading}
          >
            查询
          </Button>

        </Space>
        
        {activeTab === 'info' ? (
          <Table<FundInfo>
            columns={fundInfoColumns}
            dataSource={fundInfoData}
            rowKey="fund_code"
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range?.[0]}-${range?.[1]} 条，共 ${total} 条记录`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={handleTableChange}
            scroll={{ x: 1200 }}
          />
        ) : (
          <Table<FundDataItem>
            columns={netValueColumns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range?.[0]}-${range?.[1]} 条，共 ${total} 条记录`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            onChange={handleTableChange}
            scroll={{ x: 1200 }}
          />
        )}
      </Card>

      <Modal
        title="基金详细信息"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedFundDetail && (
          <Descriptions bordered column={2} size="small">
            <Descriptions.Item label="基金代码" span={1}>
              {selectedFundDetail.fund_code}
            </Descriptions.Item>
            <Descriptions.Item label="基金名称" span={1}>
              {selectedFundDetail.fund_name}
            </Descriptions.Item>
            <Descriptions.Item label="基金全称" span={2}>
              {selectedFundDetail.fund_full_name || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="基金类型" span={1}>
              <Tag color={getTypeColor(selectedFundDetail.fund_type)}>
                {selectedFundDetail.fund_type || '-'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="成立日期" span={1}>
              {selectedFundDetail.establishment_date || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="管理公司" span={1}>
              {selectedFundDetail.fund_company || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="基金经理" span={1}>
              {selectedFundDetail.fund_manager || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="托管银行" span={1}>
              {selectedFundDetail.custodian_bank || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="基金规模" span={1}>
              {selectedFundDetail.latest_scale || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="评级机构" span={1}>
              {selectedFundDetail.rating_agency || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="基金评级" span={1}>
              {selectedFundDetail.fund_rating || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="投资目标" span={2}>
              {selectedFundDetail.investment_objective || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="投资策略" span={2}>
              {selectedFundDetail.investment_strategy || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="业绩比较基准" span={2}>
              {selectedFundDetail.performance_benchmark || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间" span={2}>
              {dayjs(selectedFundDetail.updated_at).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 净值历史模态框 */}
      <Modal
        title={`基金净值历史 - ${selectedFundCode}`}
        open={navHistoryModalVisible}
        onCancel={() => setNavHistoryModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setNavHistoryModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={1200}
      >
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button 
              type={showChart ? 'primary' : 'default'}
              icon={<LineChartOutlined />}
              onClick={() => setShowChart(true)}
            >
              图表视图
            </Button>
            <Button 
              type={!showChart ? 'primary' : 'default'}
              onClick={() => setShowChart(false)}
            >
              表格视图
            </Button>
            <Select
              value={navHistoryPeriod}
              onChange={async (value) => {
                setNavHistoryPeriod(value);
                // 重新加载数据
                if (selectedFundCode) {
                  await handleShowNavHistory(selectedFundCode);
                }
              }}
              style={{ width: 120 }}
              options={[
                { label: '全部', value: 'all' },
                { label: '今年以来', value: 'ytd' },
                { label: '最近1年', value: '1y' },
                { label: '最近3年', value: '3y' },
                { label: '最近5年', value: '5y' },
                { label: '最近10年', value: '10y' },
              ]}
            />
          </Space>
        </div>
        
        {showChart ? (
          <div style={{ height: 400, marginBottom: 16 }}>
            {navHistoryLoading ? (
              <div style={{ 
                height: '100%', 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center',
                color: '#999'
              }}>
                <Spin size="large" />
                <span style={{ marginLeft: 8 }}>正在加载净值历史数据...</span>
              </div>
            ) : navHistoryData && navHistoryData.length > 0 ? (
              <ReactECharts 
                option={getChartOption()} 
                style={{ height: '100%', width: '100%' }}
                opts={{ renderer: 'canvas' }}
              />
            ) : (
              <div style={{ 
                height: '100%', 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center',
                color: '#999'
              }}>
                暂无数据
              </div>
            )}
          </div>
        ) : (
          <Table
            columns={navHistoryColumns}
            dataSource={navHistoryData}
            loading={navHistoryLoading}
            rowKey="id"
            pagination={{
              pageSize: 100,  // 增加默认分页大小
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              pageSizeOptions: ['50', '100', '200', '500', '1000'],  // 支持更大的分页选项
            }}
            scroll={{ x: 800, y: 600 }}  // 增加高度限制，提供更好的滚动体验
            size="small"
          />
        )}
      </Modal>
    </div>
  );
};

export default FundData;